/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package beans;

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 *
 * @author Regina
 */
public class Email 
{
        private final String HOST_KEY = "mail.smtp.host";
	private final String HOST_VALUE = "smtp.gmail.com";
	private final String SOCKET_PORT_KEY = "mail.smtp.socketFactory.port";
	private final String SOCKET_PORT_VALUE = "465";
	private final String EMAIL_SERVER_ACCOUNT = "agiles.server@gmail.com";
	private final String EMAIL_SERVER_PASSWORD = "procesosagiles2012";
	
	public Email()
        {
	}
	
	
	private String formatearEmails(String emails) {
		StringBuilder builder = new StringBuilder();
		String[] listaEmails = emails.split(";");
		
		if(listaEmails.length>1){
			for (String email : listaEmails) {
				builder.append(email.trim());
				builder.append(",");
			}
		}
                else{
                    builder.append(emails);
                }
		
		return builder.toString();
	}
	
	private void enviarCorreo(String subject, String mensaje, String emails) {
		Properties props = new Properties();
		props.put(HOST_KEY, HOST_VALUE);
		props.put(SOCKET_PORT_KEY, SOCKET_PORT_VALUE);
		props.put("mail.smtp.socketFactory.class",
				"javax.net.ssl.SSLSocketFactory");
		
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.port", "465");
 
		Session session = Session.getDefaultInstance(props,
			new javax.mail.Authenticator() {
            @Override
				protected PasswordAuthentication getPasswordAuthentication() {
					return new PasswordAuthentication(EMAIL_SERVER_ACCOUNT,EMAIL_SERVER_PASSWORD);
				}
			});
 
		try {
 
			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress(EMAIL_SERVER_ACCOUNT));
			message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(emails));
			message.setSubject(subject);
			message.setText(mensaje);
 
			Transport.send(message);
 
		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}
	}
	
	public void enviar(String subject, String mensaje, String emails)
        {
		String emailsFormateados = formatearEmails(emails);
		enviarCorreo(subject, mensaje, emailsFormateados);
	}
}
